package org.dsapr.codegen.generator;

import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;

import javax.lang.model.element.Modifier;
import java.util.List;
import java.util.Map;

public class MethodSpecGenerator {
    private final Class methodAnnotation;
    private final Modifier methodModifier;
    private final TypeName returns;
    private final String methodName;
    private final List<ParameterSpec> methodParameters;
    private final Map<String, Object[]> statementBody;

    public MethodSpecGenerator(Class methodAnnotation,
                               Modifier methodModifier,
                               TypeName returns,
                               String methodName,
                               List<ParameterSpec> methodParameters,
                               Map<String, Object[]> statementBody) {
        this.methodAnnotation = methodAnnotation;
        this.methodModifier = methodModifier;
        this.returns = returns;
        this.methodName = methodName;
        this.methodParameters = methodParameters;
        this.statementBody = statementBody;
    }

    public MethodSpec generate() {
        return MethodSpec.methodBuilder(methodName)
                .addAnnotation(methodAnnotation)
                .addModifiers(methodModifier)
                .addParameters(methodParameters)
                .addException(Exception.class)
                .returns(returns)
                .addCode(setMethodBody())
                .build();
    }

    private CodeBlock setMethodBody() {
        CodeBlock.Builder methodBody = CodeBlock.builder();
        statementBody.forEach(methodBody::addStatement);
        return methodBody.build();
    }
}
